# coding utf-8
from pipelineStarter_ui import Ui_MainWindow
from Software_Set_Run import Software_Set 

#import Software_Set_Run
from PyQt6.QtWidgets import QApplication,QListWidgetItem,QMainWindow, QTreeWidgetItem,QHeaderView,QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy, QPushButton, QGroupBox, QGridLayout
from PyQt6.QtGui import QFont
import os,json,subprocess
from os.path import join, isfile, exists
from os import environ, listdir, makedirs, pathsep, startfile
import sys
class mainWindow(Ui_MainWindow, QMainWindow):
    Software ={}
    ProjecinfoPath = 'H:/QL_tool_file/Window_Tool/Logical File/SoftwareStarter/Projecinfo/'
    def __init__(self):
        super(mainWindow, self).__init__()
        self.setupUi(self)

        self.background_color()
        self.listWidget.itemSelectionChanged.connect(lambda *args: self.set_Projec_items())
        self.treeWidget.itemDoubleClicked.connect(lambda *args: self.on_item_double_clicked())

        #self.initUI()
        for i in os.listdir(self.ProjecinfoPath):
            if i.endswith('.json'):
                ProjecName = i.split('.')[0]
                item = QListWidgetItem(ProjecName)
                font = QFont()
                font.setPointSize(20)
                item.setFont(font)
                self.listWidget.addItem(item)

    def set_Projec_items(self):
        self.software =''
        self.treeWidget.clear()
        selected_items = self.listWidget.selectedItems()   
        for item in selected_items:
            self.ProjecinfoPath
            with open(self.ProjecinfoPath + item.text() +'.json', 'r', encoding='utf8') as fp:
                self.json_data = json.load(fp)  # 读取json文件
                 
                for Software in self.json_data["Softwares"]:
                    print(Software["Software_Name"])
                    child2 = QTreeWidgetItem(self.treeWidget, [Software["Software_Name"]])
                    child2.setText(1, "Data 1")
        

    def on_item_double_clicked(self):
        proc_env = environ.copy()
        selected_items = self.treeWidget.selectedItems()
        for item in selected_items:
            # 获取选中项的数据
            text = item.text(0)  # 获取第一列的文本数据
            column_count = item.columnCount()  # 获取列数
            data = []
            for column in range(column_count):
                data.append(item.text(column))  # 获取每列的文本数据
            # 进一步处理获取到的数据
            #print("选中的文本:", text)
            #print("选中项的数据:", data)

        for Software in self.json_data["Softwares"]:
            if text == Software["Software_Name"]:
                launch_path = Software["Software_Path"]
                if launch_path:
                    for env_var in  Software["EnvironmentVariables"]:
                        print(env_var)
                        if env_var['Key'] in proc_env.keys():
                            proc_env[env_var['Key']] += pathsep + env_var['Value']
                        else:
                            proc_env[env_var['Key']] = env_var['Value']
            #print(proc_env)
            # 设置启动参数
            proc_args = []
            proc_args.append(launch_path)
            try:
                for arg in Software['Arguments']:
                    proc_args.append(arg)
            except KeyError:
                print('没有参数')
            print(proc_args)
            #print(proc_env)
            subprocess.Popen(proc_args, env= proc_env)


    def initUI(self):
        self.actiontianjia.triggered.connect(self.openSecondWindow)
        
    def openSecondWindow(self):
        #Software_Set().kaishi()
        for qt in QApplication.topLevelWidgets():
            print(qt.objectName())
            if qt.windowTitle() == u'aaaaaaaaaaaaaaaaaa':
                qt.close()
                #app.quit()
        MWin = Software_Set()
        
        MWin.show()
        '''
        window = Software_Set()
        window.show()'''

    def background_color(self):
        header = self.treeWidget.header()

        # 设置表头样式
        headerStyleSheet = """
        QHeaderView::section {
            background-color: rgb(47, 47, 47);   /* 设置表头背景颜色 */
            color: #FFFFFF;   /* 设置表头文字颜色 */
        }
        """
        header.setStyleSheet(headerStyleSheet)
        '''
        # 设置Item样式
        itemStyleSheet = """
        QTreeWidget::item {
            background-color: #00FF00;   /* 设置Item区域背景颜色 */
            color: #000000;   /* 设置Item区域文字颜色 */
        }
        """
        self.treeWidget.setStyleSheet(itemStyleSheet)
        '''

        # 设置整个QTreeWidget的背景颜色
        styleSheet = """
        QTreeWidget {
            background-color: rgb(77, 77, 77);   /* 设置整个背景颜色 */
            color: #FFFFFF;   /* 设置文字颜色 */
        }
        """
        self.treeWidget.setStyleSheet(styleSheet)

        self.treeWidget.header().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)  # 自动调整列宽

        #header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
        header.resizeSection(1, 200)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = mainWindow()
    main.show()

    sys.exit(app.exec())
'''
if __name__ == '__main__':
    app = QApplication([]) if not QApplication.instance() else None
    MWin = mainWindow()
    for qt in QApplication.topLevelWidgets():
        if qt.windowTitle() == u'mainWindow':
            qt.close()
    MWin.show()
    app.exec() if app else None'''